const HtmlWebpackPlugin = require('html-webpack-plugin');
const { resolveApp } = require('./resolve');
const package = require(`${resolveApp('')}/package.json`);
const isMobile = package.name.includes('mobile');

/**
 * 注入图标和主题的插件，包含一大堆的业务逻辑
 * @options { buildVersion: string }
 */
class InsertIconThemePlugin {
  constructor(options) {
    this.options = options || {};
  }

  apply(compiler) {
    const { buildVersion } = this.options;

    compiler.hooks.compilation.tap('InsertIconThemePlugin', (compilation) => {
      HtmlWebpackPlugin.getHooks(compilation).afterTemplateExecution.tap(
        'InsertIconThemePlugin',
        (data) => {
          const cssPath = '/theme/sy-theme.css',
            jsPath = '/icon/sy-icon.js',
            themeStorageKey = isMobile ? 'themeMobileStorageKey' : 'themeStorageKey';

          // 将head替换成body 原因是新增得script会一定程度阻塞body的渲染 影响到图标导致报错
          data.html = data.html.replace(
            /<body(.*)>/,
            `<body$1>
            <script id="sy-assets-script">
                var publicBaseUrl = localStorage.getItem('publicBaseUrl')

                var link = document.createElement('link')
                var script = document.createElement('script')

                var themeStorageKey = localStorage.getItem('${themeStorageKey}');
                var iconStorageKey = localStorage.getItem('iconStorageKey')

                if(themeStorageKey && publicBaseUrl) {
                  link.href = publicBaseUrl + '/' + themeStorageKey
                } else {
                  link.href = '/main/static' + '${cssPath}'
                }

                link.rel = 'stylesheet'
                link.type = 'text/css'
                link.id = 'sy-theme-link'

                if(iconStorageKey && publicBaseUrl) {
                  script.src = publicBaseUrl + '/' + iconStorageKey
                } else {
                  script.src = '/main/static' + '${jsPath}'
                }

                script.id = 'sy-icon-script'

                script.onerror = function () {
                  var tempScript = document.createElement('script')
                  tempScript.src = '/main/static' + '${jsPath}'
                  document.head.appendChild(tempScript)
                }

                script.onload = function () {

                  if (!String.prototype.replaceAll) {
                    String.prototype.replaceAll = function(str, newStr){

                      // If a regex pattern
                      if (Object.prototype.toString.call(str).toLowerCase() === '[object regexp]') {
                        return this.replace(str, newStr);
                      }

                      // If a string
                      return this.replace(new RegExp(str, 'g'), newStr);

                    };
                  }

                  if(window.document.addEventListener) {
                    window.document.dispatchEvent(new Event('DOMContentLoaded', {
                      bubbles: true,
                      cancelable: true
                    }))
                  } else {
                    window.document.fireEvent('onreadystatechange')
                  }
                }

                document.head.appendChild(link)
                document.head.appendChild(script)

            // 当前版本${buildVersion}
          </script>
        `,
          );
        },
      );
    });
  }
}

module.exports = InsertIconThemePlugin;
